import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import { useLocation } from 'react-router-dom';
import { saveAs } from 'file-saver';

const ExcelReader = () => {
    const [data, setData] = useState([]);
    const [columns, setColumns] = useState([]);
    const [tableData, setTableData] = useState([]);
    const [newTableData, setNewTableData] = useState([]);
    const [mergedData, setMergedData] = useState([]);
    const [fileName, setFileName] = useState('merged_data');
    const [backendData, setBackendData] = useState([]);
    const location = useLocation();
    const { rowsDatas, selectedTableName } = location.state || { rowsDatas: [], selectedTableName: 'DEMO' };

    const handleFileChange = (event) => {
        const file = event.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const binaryStr = e.target.result;
                const workbook = XLSX.read(binaryStr, { type: 'binary' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const jsonData = XLSX.utils.sheet_to_json(worksheet);
                setData(jsonData);
                setColumns(Object.keys(jsonData[0]));
            } catch (error) {
                console.error('Error reading Excel file:', error);
            }
        };
        reader.readAsBinaryString(file);
    };

    const handleSelectChange = (id, field, value) => {
        const updatedData = tableData.map((row) => {
            if (row.id === id) {
                return { ...row, [field]: value };
            }
            return row;
        });
        setTableData(updatedData);
    };

    const addRow = () => {
        const newRow = {
            id: tableData.length + 1,
            Excel: '',
            System: ''
        };
        setTableData([...tableData, newRow]);
    };

    const updateTableData = (tableData, rowsDatas) => {
        const updatedTableData = tableData.map((row) => {
            for (const rowsData of rowsDatas) {
                if (row.System === rowsData.comments) {
                    return {
                        ...row,
                        System: rowsData.columnName
                    };
                }
            }
            return row;
        });
        return updatedTableData;
    };

    const handleNextStep = async () => {
        try {
            const updatedTableData = updateTableData(tableData, rowsDatas);
            setNewTableData(updatedTableData);

            setMergedData(data);

            const excelData = {};
            const systemData = [];
            let checkedData = '';
            let excelCheckColumn = '';
            rowsDatas.forEach((rowsData) => {
                systemData.push(rowsData.columnName);
            });

            tableData.forEach((row) => {
                if (row.Excel && row.System) {
                    const systemColumnData = rowsDatas.find((data) => data.comments === row.System);
                    const systemColumnName = systemColumnData ? systemColumnData.columnName : '未找到对应 columnName';
                    const excelColumnValues = data.map((excelRow) => excelRow[row.Excel]);

                    excelData[systemColumnName] = excelColumnValues;
                    if (systemColumnData) {
                        const systemColumnName = systemColumnData.columnName;
                        console.log('选中的字段 system.columnName:', systemColumnName);
                        if (checkedData) {
                            checkedData += ',' + systemColumnName;
                        } else {
                            checkedData = systemColumnName;
                        }
                    }
                    excelCheckColumn = row.Excel;
                    console.log("excelCheckColumn：", excelCheckColumn);
                    console.log(`Excel 列名: ${row.Excel}, 对应的数据:`, excelColumnValues);
                }
            });

            const result = {
                "excel": [excelData],
                "system": systemData,
                "tableName": selectedTableName
            };

            const response = await fetch('http://127.0.0.1:9991/api/admin/demo/relevanceSelect', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(result)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const responseData = await response.json();

            const filteredData = responseData.data.map((item) => {
                const values = [];
                const fields = checkedData.split(',');
                fields.forEach((field) => {
                    values.push(item.hasOwnProperty(field) ? item[field] : null);
                });
                return values;
            });
            const flattenedData = [].concat(...filteredData);
            console.log("system key:", checkedData, "system value:", flattenedData);
            setBackendData(filteredData);

            if (Array.isArray(responseData.data)) {
                const newMergedData = data.map((excelRow) => {
                    let newRow = { ...excelRow };
                    // 假设 Excel.comments 对应的列名是 comments
                    console.log("excelCheckColumn:", excelCheckColumn);
                    const commentValue = excelRow[excelCheckColumn];
                    if (commentValue) {
                        const commentValueStr = String(commentValue).trim(); // 将 commentValue 转换为字符串并去除首尾空格
                        responseData.data.forEach((backendItem) => {
                            const fields = checkedData.split(',');
                            fields.forEach((field) => {
                                const backendValue = backendItem[field];
                                const backendValueStr = backendValue!== null && backendValue!== undefined? String(backendValue).trim() : ''; // 将后端值转换为字符串并去除首尾空格
                                if (backendValueStr === commentValueStr) {
                                    console.log("commentValue:", commentValue);
                                    console.log("backendItem[field]:", backendItem[field]);
                                    newRow = { ...newRow, ...backendItem };
                                }
                            });
                        });
                    }
                    return newRow;
                });
                setMergedData(newMergedData);
            } else if (typeof responseData === 'object' && responseData!== null) {
                Object.entries(responseData).forEach(([key, value]) => {
                    console.log(`${key}:`, value);
                });
            } else {
                console.log('后端返回的数据不是数组或对象:', responseData);
            }

        } catch (error) {
            console.error('Error calling backend API:', error);
        }
    };

    const exportToExcel = () => {
        console.log('导出函数被调用，mergedData:', mergedData);
        if (mergedData.length === 0) {
            alert('没有数据可导出！');
            return;
        }
        try {
            const columnMapping = {};
            tableData.forEach((row) => {
                if (row.Excel && row.System) {
                    columnMapping[row.Excel] = row.System;
                }
            });

            const transformedData = mergedData.map((row) => {
                const newRow = {};
                Object.keys(row).forEach((key) => {
                    if (columnMapping[key]) {
                        newRow[columnMapping[key]] = row[key];
                    } else {
                        newRow[key] = row[key];
                    }
                });
                return newRow;
            });

            const worksheet = XLSX.utils.json_to_sheet(transformedData);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });

            const buf = new ArrayBuffer(wbout.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i < wbout.length; i++) {
                view[i] = wbout.charCodeAt(i) & 0xFF;
            }

            const blob = new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            saveAs(blob, `${fileName}.xlsx`);
        } catch (error) {
            console.error('导出 Excel 时出现错误:', error);
            alert('导出 Excel 时出现错误，请检查控制台日志。');
        }
    };

    useEffect(() => {
        console.log('newTableData 更新:', newTableData);
    }, [newTableData]);

    return (
        <div style={{ padding: '20px' }}>
            <div>
                <h1>Excel 导入数据</h1>
                <input type="file" accept=".xlsx, .xls" onChange={handleFileChange} />
                {data.length > 0 && (
                    <table style={{ marginTop: '20px', borderCollapse: 'collapse', width: '100%' }}>
                        <thead>
                            <tr>
                                {columns.map((key) => (
                                    <th key={key} style={{ border: '1px solid black', padding: '8px' }}>{key}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {data.map((row, index) => (
                                <tr key={index}>
                                    {columns.map((key) => (
                                        <td key={key} style={{ border: '1px solid black', padding: '8px' }}>{row[key]}</td>
                                    ))}
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
            </div>
            <div style={{ padding: '20px' }}>
                <h1>关联字段</h1>
                <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '20px' }}>
                    <thead>
                        <tr>
                            <th style={{ border: '1px solid #ccc', padding: '8px' }}>ID</th>
                            <th style={{ border: '1px solid #ccc', padding: '8px' }}>Excel</th>
                            <th style={{ border: '1px solid #ccc', padding: '8px' }}>System</th>
                        </tr>
                    </thead>
                    <tbody>
                        {tableData.map((row) => (
                            <tr key={row.id}>
                                <td style={{ border: '1px solid #ccc', padding: '8px' }}>{row.id}</td>
                                <td style={{ border: '1px solid #ccc', padding: '8px' }}>
                                    <select onChange={(e) => handleSelectChange(row.id, 'Excel', e.target.value)}>
                                        <option value="">请选择</option>
                                        {columns.map((column, index) => (
                                            <option key={index} value={column}>
                                                {column}
                                            </option>
                                        ))}
                                    </select>
                                </td>
                                <td style={{ border: '1px solid #ccc', padding: '8px' }}>
                                    <select onChange={(e) => handleSelectChange(row.id, 'System', e.target.value)}>
                                        <option value="">请选择</option>
                                        {rowsDatas.map((rowsData, index) => (
                                            <option key={index} value={rowsData.comments}>
                                                {rowsData.comments}
                                            </option>
                                        ))}
                                    </select>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                <button
                    onClick={addRow}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: '40px',
                        height: '40px',
                        borderRadius: '50%',
                        backgroundColor: '#007bff',
                        color: '#fff',
                        border: 'none',
                        cursor: 'pointer',
                        fontSize: '24px'
                    }}
                >
                    +
                </button>
            </div>
            <div>
                <button onClick={handleNextStep}>下一步</button>
            </div>
            {mergedData.length > 0 && (
                <div style={{ padding: '20px' }}>
                    <h1>导出数据回显</h1>
                    <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '20px' }}>
                        <thead>
                            <tr>
                                {Object.keys(mergedData[0]).map((key) => (
                                    <th key={key} style={{ border: '1px solid #ccc', padding: '8px' }}>{key}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {mergedData.map((row, index) => (
                                <tr key={index}>
                                    {Object.keys(row).map((key) => (
                                        <td key={key} style={{ border: '1px solid #ccc', padding: '8px' }}>{row[key]}</td>
                                    ))}
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    <button onClick={exportToExcel} style={{ marginTop: '20px', padding: '10px 20px', backgroundColor: '#28a745', color: '#fff', border: 'none', cursor: 'pointer' }}>
                        导出为 Excel
                    </button>
                </div>
            )}
        </div>
    );
};

export default ExcelReader;